package pri.service.product;

import cn.hutool.core.util.IdUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class ImgServiceImpl implements ImgService{



    @Override
    public String saveImg(String basePath, MultipartFile imgFile) {
        if(basePath == null || imgFile == null){
            return "";
        }

        return fileSave(imgFile, basePath, "assets\\images\\");
    }

    @Override
    public List<String> saveImgs(String basePath, List<MultipartFile> imgFiles) {
        List<String> urls = new ArrayList<>();

        if(basePath==null || imgFiles == null) return urls;

        String path = "assets\\images\\";

        for (MultipartFile imgFile : imgFiles) {
            urls.add(fileSave(imgFile, basePath, path));
        }

        return urls;
    }


    /**
     * 将文件存入磁盘中,路径在本项项目WebContent目录下
     */
    public String fileSave(MultipartFile file,String basePath, String path){
        return fileSave(file,basePath,path, IdUtil.simpleUUID());
    }

    /**
     * 将文件存入磁盘中,路径在本项项目WebContent目录下,指定存储文件名
     */
    public String fileSave(MultipartFile file,String basePath, String path,String memoryName){
        String realPath = basePath + path;
        File targetDir = new File(realPath);
        if(!targetDir.exists()){
            targetDir.mkdirs();
        }

//        获得原文件名
        String fileName = file.getOriginalFilename();
//        获得原文件后缀名
        String fileSuffix = fileName.substring(fileName.lastIndexOf(".")+1);

//        防止文件重名,随机生成文件的存储名
//        String memoryName = MyUtil.getLongId()+"."+fileSuffix;


        memoryName = memoryName + "."+fileSuffix;

//        生成文件src路径
        String src = path +"\\"+ memoryName;
        File targetFile = new File(realPath,memoryName);
//         保存到磁盘
        try {
            file.transferTo(targetFile);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        return src;
    }




    /**
     * 删除本项目下的文件
     */
    public static void deleteFile(String basePath,String path){
        String absolutePath = basePath + path;
        File file = new File(absolutePath);
        file.delete();
    }



}
